package org.marsdonne.audits.resolver;

import graphql.kickstart.tools.GraphQLQueryResolver;
import org.marsdonne.audits.Auth;
import org.marsdonne.audits.Exception;
import org.marsdonne.audits.ExceptionFilters;
import org.marsdonne.audits.repos.ChangeRepos;
import org.marsdonne.audits.repos.ExceptionRepos;
import org.marsdonne.commons.jpa.FilterSpecSupport;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
public class ExceptionQueryResolver implements GraphQLQueryResolver, FilterSpecSupport<Exception> {
    @Resource
    private ExceptionRepos repos;

    public Iterable<Exception> getExceptions(ExceptionFilters filters) {
        Specification<Exception> spec = null;

        if(filters != null) {
            if(filters.getServiceId() != null)
                spec = by("serviceId", filters.getServiceId());

            if(filters.getType() != null) {
                Specification<Exception> specPart = by("type", filters.getType());
                spec = (spec == null) ? specPart : spec.and(specPart);
            }

            if(filters.getDateLogged() != null) {
                Specification<Exception> specPart = by("dateLogged", filters.getDateLogged());
                spec = (spec == null) ? specPart : spec.and(specPart);
            }
        }

        Sort sort = Sort.by("dateLogged").descending();

        if (spec == null)
            return repos.findAll(sort);
        else
            return repos.findAll(spec, sort);
    }
}
